package com.ruoyi.system.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.poi.EasyexcelUtils;
import com.ruoyi.system.domain.excel.SysOperLogExcel;
import com.ruoyi.system.service.ISysDictDataService;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.InnerAuth;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.system.api.domain.SysOperLog;
import com.ruoyi.system.service.ISysOperLogService;

/**
 * 操作日志记录
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/operlog")
public class SysOperlogController extends BaseController
{
    @Autowired
    private ISysOperLogService operLogService;

    @Autowired
    private ISysDictDataService dictDataService;

    @RequiresPermissions("system:operlog:list")
    @GetMapping("/list")
    public TableDataInfo list(SysOperLog operLog)
    {
        startPage();
        List<SysOperLog> list = operLogService.selectOperLogList(operLog);
        return getDataTable(list);
    }

    @Log(title = "导出操作日志", businessType = BusinessType.EXPORT)
    @RequiresPermissions("system:operlog:export")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysOperLog operLog)
    {
        List<SysOperLog> list = operLogService.selectOperLogList(operLog);
        // 转换为导出实体类
        List<SysOperLogExcel> excelList = list.stream().map(item -> {
            SysOperLogExcel excel = new SysOperLogExcel();
            excel.setOperId(item.getOperId());
            excel.setTitle(item.getTitle());
            // 使用字典服务将业务类型代码转换为文本描述
            if (item.getBusinessType() != null) {
                String businessTypeText = dictDataService.selectDictLabel("sys_oper_type", item.getBusinessType().toString());
                excel.setBusinessType(StringUtils.isNotEmpty(businessTypeText) ? businessTypeText : "未知");
            } else {
                excel.setBusinessType("未知");
            }
            excel.setMethod(item.getMethod());
            excel.setRequestMethod(item.getRequestMethod());
            // 使用字典服务将操作类别代码转换为文本描述
            if (item.getOperatorType() != null) {
                String operatorTypeText = dictDataService.selectDictLabel("operation_type", item.getOperatorType().toString());
                excel.setOperatorType(StringUtils.isNotEmpty(operatorTypeText) ? operatorTypeText : "未知");
            } else {
                excel.setOperatorType("未知");
            }
            excel.setOperName(item.getOperName());
            excel.setDeptName(item.getDeptName());
            excel.setOperUrl(item.getOperUrl());
            excel.setOperIp(item.getOperIp());
            excel.setOperParam(item.getOperParam());
            excel.setJsonResult(item.getJsonResult());
            // 使用字典服务将操作状态代码转换为文本描述
            if (item.getStatus() != null) {
                String statusText = dictDataService.selectDictLabel("sys_common_status", item.getStatus().toString());
                excel.setStatus(StringUtils.isNotEmpty(statusText) ? statusText : "未知");
            } else {
                excel.setStatus("未知");
            }
            excel.setErrorMsg(item.getErrorMsg());
            excel.setOperTime(item.getOperTime());
            excel.setCostTime(item.getCostTime());
            return excel;
        }).collect(java.util.stream.Collectors.toList());

        // 使用EasyExcel导出
        EasyexcelUtils.exportExcel(response, excelList, "操作日志", SysOperLogExcel.class);
    }



    @Log(title = "删除操作日志", businessType = BusinessType.DELETE)
    @RequiresPermissions("system:operlog:remove")
    @DeleteMapping("/{operIds}")
    public AjaxResult remove(@PathVariable Long[] operIds)
    {
        return toAjax(operLogService.deleteOperLogByIds(operIds));
    }

    @RequiresPermissions("system:operlog:remove")
    @Log(title = "清空操作日志", businessType = BusinessType.CLEAN)
    @DeleteMapping("/clean")
    public AjaxResult clean()
    {
        operLogService.cleanOperLog();
        return success();
    }

    @InnerAuth
    @PostMapping
    public AjaxResult add(@RequestBody SysOperLog operLog)
    {
        return toAjax(operLogService.insertOperlog(operLog));
    }

    /**
     * 获取所有统计数据（首页用）
     * 
     * @param days 天数范围（默认7天）
     * @return 所有统计数据
     */
    @Operation(summary = "获取所有统计数据（首页用）")
    @GetMapping("/dashboardStats")
    public AjaxResult getDashboardStats(@RequestParam(defaultValue = "7") Integer days)
    {
        Map<String, Object> stats = new HashMap<>();
        stats.put("todayCount", operLogService.getTodayCount());
        stats.put("thisWeekCount", operLogService.getThisWeekCount());
        stats.put("thisMonthCount", operLogService.getThisMonthCount());
        stats.put("dailyTrend", operLogService.getDailyTrend(days));
        stats.put("operatorDistribution", operLogService.getOperatorDistribution(days));
        stats.put("moduleCallCount", operLogService.getModuleCallCount(days));
        // 添加操作人员排行TOP10数据
        stats.put("operatorTop10", operLogService.getOperatorTop10(days));
        return AjaxResult.success(stats);
    }
}
